// UserServiceImpl.java
package com.ny.service.impl;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.UserService;
import com.ny.service.impl.EmailService;
import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private EmailService emailService;
    
    // 使用ConcurrentHashMap作为验证码存储的备选方案（当Redis不可用时）
    private Map<String, String> codeStorage = new ConcurrentHashMap<>();
    private Map<String, Long> codeExpiry = new ConcurrentHashMap<>();

    @Override
    public User findNickname(String nickname) {
        return userMapper.findNickname(nickname);
    }

    // 实现注册方法
    @Override
    public boolean registerUser(User user) {
        // 对用户密码进行加密
        String encryptedPassword = PasswordUtil.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        
        // 设置创建时间
        user.setCreatedTime(new Date());
        
        // 保存用户信息
        int result = userMapper.insertUser(user);
        return result > 0;
    }
    // 实现登录方法
    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        // 登录时也需要对输入的密码进行加密后再比较
        if (user != null && PasswordUtil.checkPassword(password, user.getPassword())) {
            return user;
        }
        return null;
    }
    
    // 实现根据邮箱查询用户的方法
    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }
    
    // 实现根据邮箱更新密码的方法
    @Override
    public int updatePassword(String password, String email) {
        // 密码加密
        String pwd = PasswordUtil.encryptPassword(password);
        return userMapper.updatePassword(pwd, email);
    }
    
    // 给邮箱发送验证码
    @Override
    public void sendToEmail(String toEmail) {
        // 生成验证码
        String code = emailService.getCode();
        // 执行发送验证码的逻辑
        emailService.sendEmail(toEmail, code);
        // 将验证码存储到内存中，设置5分钟过期时间
        codeStorage.put("code:" + toEmail, code);
        codeExpiry.put("code:" + toEmail, System.currentTimeMillis() + 5 * 60 * 1000);
    }
    
    // 验证验证码并修改密码
    @Override
    public Result verifyCodeAndUpdatePassword(String email, String code, String newPassword) {
        String key = "code:" + email;
        String storedCode = codeStorage.get(key);
        Long expiryTime = codeExpiry.get(key);
        
        // 检查验证码是否存在
        if (storedCode == null || expiryTime == null) {
            return Result.error("验证码已过期");
        }
        
        // 检查验证码是否过期
        if (System.currentTimeMillis() > expiryTime) {
            codeStorage.remove(key);
            codeExpiry.remove(key);
            return Result.error("验证码已过期");
        }
        
        if (!storedCode.equals(code)) {
            return Result.error("验证码错误");
        }
        
        // 验证码正确，执行修改密码操作
        int result = updatePassword(newPassword, email);
        
        if (result > 0) {
            // 删除已使用的验证码
            codeStorage.remove(key);
            codeExpiry.remove(key);
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }
    }
}